import redis
import json
from django.conf import settings

class RedisClient:
    """
    Redis客户端工具类，用于连接和操作Redis服务器
    """
    def __init__(self):
        # 从配置中获取Redis连接信息
        self.host = getattr(settings, 'REDIS_HOST', 'localhost')
        self.port = getattr(settings, 'REDIS_PORT', 6379)
        self.db = getattr(settings, 'REDIS_DB', 0)
        self.password = getattr(settings, 'REDIS_PASSWORD', None)
        self.connection_pool = None
        self.client = None
        self.connect()

    def connect(self):
        """连接到Redis服务器"""
        try:
            self.connection_pool = redis.ConnectionPool(
                host=self.host,
                port=self.port,
                db=self.db,
                password=self.password,
                decode_responses=True  # 自动解码为字符串
            )
            self.client = redis.Redis(connection_pool=self.connection_pool)
            # 测试连接
            self.client.ping()
            print(f"成功连接到Redis服务器: {self.host}:{self.port} 数据库: {self.db}")
        except Exception as e:
            print(f"连接Redis服务器失败: {str(e)}")
            raise

    def get(self, key):
        """获取键值"""
        try:
            return self.client.get(key)
        except Exception as e:
            print(f"获取Redis键值失败: {str(e)}")
            self.connect()  # 尝试重新连接
            return self.client.get(key)

    def set(self, key, value, expire=None):
        """设置键值，可选过期时间"""
        try:
            if expire:
                self.client.set(key, value, ex=expire)
            else:
                self.client.set(key, value)
            return True
        except Exception as e:
            print(f"设置Redis键值失败: {str(e)}")
            self.connect()  # 尝试重新连接
            if expire:
                self.client.set(key, value, ex=expire)
            else:
                self.client.set(key, value)
            return True

    def delete(self, key):
        """删除键"""
        try:
            return self.client.delete(key)
        except Exception as e:
            print(f"删除Redis键失败: {str(e)}")
            self.connect()  # 尝试重新连接
            return self.client.delete(key)

    def hset(self, name, key, value):
        """设置哈希表字段"""
        try:
            self.client.hset(name, key, value)
            return True
        except Exception as e:
            print(f"设置Redis哈希表字段失败: {str(e)}")
            self.connect()  # 尝试重新连接
            self.client.hset(name, key, value)
            return True

    def hget(self, name, key):
        """获取哈希表字段"""
        try:
            return self.client.hget(name, key)
        except Exception as e:
            print(f"获取Redis哈希表字段失败: {str(e)}")
            self.connect()  # 尝试重新连接
            return self.client.hget(name, key)

    def hgetall(self, name):
        """获取哈希表所有字段"""
        try:
            return self.client.hgetall(name)
        except Exception as e:
            print(f"获取Redis哈希表所有字段失败: {str(e)}")
            self.connect()  # 尝试重新连接
            return self.client.hgetall(name)

    def set_json(self, key, value, expire=None):
        """存储JSON对象"""
        try:
            json_str = json.dumps(value)
            if expire:
                self.client.set(key, json_str, ex=expire)
            else:
                self.client.set(key, json_str)
            return True
        except Exception as e:
            print(f"存储JSON对象失败: {str(e)}")
            return False

    def get_json(self, key):
        """获取JSON对象"""
        try:
            json_str = self.client.get(key)
            if json_str:
                return json.loads(json_str)
            return None
        except Exception as e:
            print(f"获取JSON对象失败: {str(e)}")
            return None

# 创建Redis客户端实例
redis_client = RedisClient()


def get_redis_client():
    """获取Redis客户端实例"""
    return redis_client